﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using eeenno.ReaderEngine.Utilities;

namespace eeenno.ReaderEngine.Adapters
{
    public class TwitterEngine
    {
        private static string _UPDATE_URL = "https://twitter.com/statuses/update.xml";

        public static bool PostTweet(string tweet, string username, string password)
        {
            HttpWebRequest tweet_request = WebManager.GetWebRequest(_UPDATE_URL+ "?source=Speeed Reader", true);
            if (tweet_request != null)
            {
                UTF8Encoding encoding = new UTF8Encoding();
                string user = Convert.ToBase64String(encoding.GetBytes(username + ":" + password));
                byte[] post_data = encoding.GetBytes("status=" + tweet);
                tweet_request.Headers.Add("Authorization", "Basic " + user);
                WebManager.bytes_transferred += tweet_request.ContentLength = post_data.Length;
                try
                {
                    using (Stream request_stream = tweet_request.GetRequestStream())
                    {
                        request_stream.Write(post_data, 0, post_data.Length);
                    }
                }
                catch (WebException e)
                {
                    LogManager.LogError("TwitterEngine.PostTweet", e.Message + " " + e.Status);
                    return false;
                }
                catch (Exception e)
                {
                    LogManager.LogError("WebManager.GetResponseStreamData", e.Message);
                    return false;
                }
                WebManager.GetResponseStreamData(tweet_request);
                return true;
            }
            return false;
        }
    }
}
